﻿using System.Diagnostics;
using U8DllPack.Controller;
using U8DllPack.Model;
using U8DllPack.Properties;
using U8DllPack.View;

namespace U8DllPack
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            Icon = Resources.pack_32;
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            Sub_Load();
        }

        private void Sub_Load()
        {
            string json = BaseCls.ReadProjJson();
            if (!json.IsNullOrWhiteSpace())
            {
                BaseCls.JsonProject = JsonHelper.Deserialize<List<Json_Project>>(json);
                Sub_ListBoxLoad();
            }
        }

        private void Sub_ListBoxLoad()
        {
            if (BaseCls.JsonProject != null && BaseCls.JsonProject.Count > 0)
            {
                foreach (Json_Project p in BaseCls.JsonProject)
                {
                    if (!(p == null || p.Id == null || p.projectname.IsNullOrWhiteSpace()))
                    {
                        Items it = new(p.Id, p.projectname);
                        lsbU8pro.Items.Add(it);
                    }
                }
            }
        }
        private void BtnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            Enabled = false;
            Sub_New();
            Enabled = true;
        }

        private void Sub_New()
        {
            FrmEdit f = new();
            DialogResult dret = f.ShowDialog();
            if (dret == DialogResult.OK)
            {
                Json_Project? project = f.UiProject;
                if (project == null) return;
                BaseCls.JsonProject ??= [];
                BaseCls.JsonProject.Add(project);
                Sub_Save();
                lsbU8pro.Items.Clear();
                Sub_ListBoxLoad();
            }
        }

        private void Sub_Save()
        {
            string json = string.Empty;
            if (BaseCls.JsonProject != null && BaseCls.JsonProject.Count > 0)
            {
                json = JsonHelper.Serialize(BaseCls.JsonProject);
            }
            BaseCls.WriteProjJson(json);
        }
        private void btnEdit_Click(object sender, EventArgs e)
        {
            Enabled = false;
            Sub_Edit();
            Enabled = true;
        }

        private void Sub_Edit()
        {
            if (lsbU8pro.SelectedItem == null)
            {
                CommFun.MsgBox("请选择左侧项目！", 1);
                lsbU8pro.Focus_Ext();
                return;
            }
            if (lsbU8pro.SelectedItem is not Items it)
            {
                CommFun.MsgBox("项目信息为空！", 1);
                lsbU8pro.Focus_Ext();
                return;
            }
            Guid? sid = it.Value as Guid?;
            if (sid.IsNull())
            {
                CommFun.MsgBox("项目编号加载错误！", 1);
                lsbU8pro.Focus_Ext();
            }
            if (BaseCls.JsonProject == null)
            {
                CommFun.MsgBox("项目列表内存表加载错误！", 1);
                return;
            }
            Json_Project? jp = BaseCls.JsonProject.Where(x => x.Id.Equals(sid!)).First();

            FrmEdit f = new()
            {
                UiProject = jp
            };
            DialogResult dret = f.ShowDialog();
            //保存返回
            //if (dret == DialogResult.OK)
            //{

            //}
        }
        private void btnDel_Click(object sender, EventArgs e)
        {
            Enabled = false;
            Sub_Del();
            Enabled = true;
        }

        private void Sub_Del()
        {
            if (lsbU8pro.SelectedItem == null)
            {
                CommFun.MsgBox("请选择左侧项目！", 1);
                lsbU8pro.Focus_Ext();
                return;
            }
            if (lsbU8pro.SelectedItem is not Items it)
            {
                CommFun.MsgBox("项目信息为空！", 1);
                lsbU8pro.Focus_Ext();
                return;
            }
            Guid? sid = it.Value as Guid?;
            if (sid.IsNull())
            {
                CommFun.MsgBox("项目编号加载错误！", 1);
                lsbU8pro.Focus_Ext();
                return;
            }
            if (BaseCls.JsonProject == null)
            {
                CommFun.MsgBox("项目列表内存表加载错误！", 1);
                return;
            }
            Json_Project? jp = BaseCls.JsonProject.Where(x => x.Id.Equals(sid!)).First();
            if (jp == null) return;
            DialogResult dret = CommFun.MsgBox("是否删除项目：" + jp.projectname + "？\r\n将删除项目所有配置文件。", 2);
            if (dret == DialogResult.No) return;
            if (!jp.projectfile.IsNullOrWhiteSpace())
            {
                BaseCls.DeleteLibsFile(jp.projectfile!);
            }
            BaseCls.JsonProject.Remove(jp);
            Sub_Save();
            lsbU8pro.Items.Clear();
            Sub_ListBoxLoad();
        }

        private void lsbU8pro_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int ix = lsbU8pro.IndexFromPoint(e.Location);
            if (ix < 0) return;
            Enabled = false;
            Sub_Edit();
            Enabled = true;
        }
        private void btnPack_Click(object sender, EventArgs e)
        {
            Enabled = false;
            Sub_Pack();
            Enabled = true;
        }

        private void Sub_Pack()
        {
            if (lsbU8pro.SelectedItem == null)
            {
                CommFun.MsgBox("请选择左侧项目！", 1);
                lsbU8pro.Focus_Ext();
                return;
            }
            if (lsbU8pro.SelectedItem is not Items it)
            {
                CommFun.MsgBox("项目信息为空！", 1);
                lsbU8pro.Focus_Ext();
                return;
            }
            Guid? sid = it.Value as Guid?;
            if (sid.IsNull())
            {
                CommFun.MsgBox("项目编号加载错误！", 1);
                lsbU8pro.Focus_Ext();
                return;
            }
            if (BaseCls.JsonProject == null)
            {
                CommFun.MsgBox("项目列表内存表加载错误！", 1);
                return;
            }
            Json_Project jp = BaseCls.JsonProject.Where(x => x.Id.Equals(sid!)).First();
            if (jp == null || jp.projectfile.IsNullOrWhiteSpace())
            {
                CommFun.MsgBox("项目信息加载错误！", 1);
                return;
            }
            string json = BaseCls.ReadLibsJson(jp.projectfile!);
            Json_ProjectInfo? pi = JsonHelper.Deserialize<Json_ProjectInfo>(json);
            if (pi == null || pi.systempath.IsNullOrWhiteSpace() || pi.dlls == null || pi.dlls.Count == 0)
            {
                CommFun.MsgBox("项目文件解析错误！", 1);
                return;
            }
            string zipfile = Path.Combine(BaseCls.LibsDir, pi.systempath + ".zip");
            if (File.Exists(zipfile)) File.Delete(zipfile);
            string temp_spath = Path.Combine(BaseCls.ZipTempDir, pi.systempath!);
            if (Directory.Exists(temp_spath))
            {
                Directory.Delete(temp_spath, true);
            }
            Directory.CreateDirectory(temp_spath);

            Json_Ver JV = new()
            {
                systempath = pi.systempath,
                ver = pi.ver,
                desc = pi.desc
            };

            foreach (Json_ProjectDlls? dll in pi.dlls)
            {
                if (dll == null || dll.filepath.IsNullOrWhiteSpace() || !File.Exists(dll.filepath) || dll.name.IsNullOrWhiteSpace()) continue;
                string fullname = Path.Combine(temp_spath, dll.name!);
                if (dll.u8ver == 0)
                {
                    JV.sharefiles ??= [];
                    Json_Dllfile d = new()
                    {
                        name = dll.name,
                        ver = dll.ver,
                        desc = dll.desc
                    };
                    JV.sharefiles.Add(d);
                }
                else if (dll.u8ver > 0)
                {
                    JV.singlefile ??= [];
                    Json_Singlefile? sf = new()
                    {
                        u8ver = CustomDataTable.Get_CusDT_Text(CustomDataTable.DT_U8ver(), dll.u8ver)
                    };
                    if (sf.u8ver.IsNullOrWhiteSpace() || dll.respath.IsNullOrWhiteSpace())
                    {
                        continue;
                    }
                    sf.respath = dll.respath;
                    sf.files ??= [];
                    Json_Dllfile d = new()
                    {
                        name = dll.name,
                        ver = dll.ver,
                        desc = dll.desc
                    };
                    sf.files.Add(d);
                    IEnumerable<Json_Singlefile> o_jvs = JV.singlefile.Where(x => x.u8ver.Equals_Ext(sf.u8ver));
                    if (!o_jvs.Any())
                    {
                        JV.singlefile.Add(sf);
                    }
                    else
                    {
                        Json_Singlefile o_jv = o_jvs.First();
                        o_jv.files ??= [];
                        o_jv.files.Add(d);
                    }
                    string s_fp = Path.Combine(temp_spath, dll.respath!);
                    fullname = Path.Combine(s_fp, dll.name!);
                    Directory.CreateDirectory(s_fp);
                }
                File.Copy(dll.filepath, fullname, true);
            }
            string ver_json = JsonHelper.Serialize(JV);
            BaseCls.WriteVerJson(ver_json);
            ZipHelper.CreateZip(zipfile, BaseCls.ZipTempDir);
            Directory.Delete(BaseCls.ZipTempDir, true);
            DialogResult dret = CommFun.MsgBox("链接库文件已成功打包！\r\n文件地址：\r\n" + zipfile + "\r\n是否打开库文件夹！", 2);
            if (dret == DialogResult.No) return;
            Process.Start("Explorer.exe", BaseCls.LibsDir);
        }
    }
}
